/**
 * All rights Reserved, Designed By Android_Robot
 *
 * @Title: MainZhiShiActivity.java
 * @Package com.jiyi.activity.main
 * @Description: TODO(用一句话描述该文件做什么)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 * @version V1.0
 */
package com.jiyi.activity.leader;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v4.widget.SwipeRefreshLayout.OnRefreshListener;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.jiyi.activity.new_maintenance.JoinMemberReadActivity;
import com.jiyi.activity.new_maintenance.MaintenanceTaskDetailActivity;
import com.jiyi.adapter.DividerItemDecoration;
import com.jiyi.adapter.recyclerview.MultiItemTypeAdapter;
import com.jiyi.adapter.recyclerview.base.ItemViewDelegate;
import com.jiyi.adapter.recyclerview.base.ViewHolder;
import com.jiyi.adapter.recyclerview.wrapper.EmptyWrapper;
import com.jiyi.bean.main.NewsListJson.NewsBean;
import com.jiyi.bean.maintenance.Task;
import com.jiyi.common.StringInterface;
import com.jiyi.common.VolleyRequest;
import com.jiyi.easemob.util.UserHelp;
import com.jiyi.event.MaintenanceTaskListEvent;
import com.jiyi.exception.SampleRefreshObserver;
import com.jiyi.inteface.ConfirmPopInterface;
import com.jiyi.inteface.OnRcvScrollListener;
import com.jiyi.inteface.WebApi;
import com.jiyi.retrofit.HttpMethods;
import com.jiyi.view.ConfirmPopView;
import com.jiyi.widget.picshow.ImagePagerActivity;
import com.swift.maintenance.R;
import com.swift.maintenance.base.AppBase;
import com.swift.maintenance.base.AppConfig;
import com.swift.maintenance.utils.ToastUtil;
import com.swift.maintenance.utils.UserInfoUtil;
import com.swift.utils.DialogTool;

import org.greenrobot.eventbus.EventBus;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @ClassName: MainZhiShiActivity
 * @Description:TODO(这里用一句话描述这个类的作用)
 * @author: HYM
 * @date: 2017-6-23 上午10:02:35
 *
 */
public class LeaderAllMaintenanceTaskFragment extends Fragment implements
        OnRefreshListener, ConfirmPopInterface {

    List<NewsBean> newsList = new ArrayList<NewsBean>();
    LayoutInflater inflater;

    @BindView(R.id.mainList)
    RecyclerView mListView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private List<Task> mTasks = new ArrayList<Task>();
    EmptyWrapper adapter;
    ViewGroup container;
    int type;

    Dialog dialog;

    // 是否刷新模式
    boolean isRefresh = false;
    int pageNo = 1;// 页码
    private final int LOAD_DATA = 5; // 加载数据事件
    private boolean loadfinish = true; // 指示数据是否加载完成
    ConfirmPopView mConfirmPopView;
    // 要被删除的任务
    int deletePosition = -1;
    // 要被删除的ID
    String deleteId = "";

    @Override
    public View onCreateView(LayoutInflater inflater,
                             @Nullable ViewGroup container, Bundle savedInstanceState) {
        View view = inflater
                .inflate(R.layout.fragment_all_wx_task, null, false);
        ButterKnife.bind(this, view);
        this.inflater = inflater;
        this.container = container;
        init();
        return view;
    }

    @Override
    public void onDestroy() {
        DialogTool.hideDialog(dialog);
        super.onDestroy();
    }

    private void init() {
        getIntentData();
        getData();
        setAdapter();
        mConfirmPopView = new ConfirmPopView(getContext(), this, "确定撤销派发的任务？", "取消", "确定撤销");
    }

    /**
     * @author: HYM
     * @Title: getIntentData
     * @Description: TODO(这里用一句话描述这个方法的作用) void
     * @date: 2017-8-30
     */
    private void getIntentData() {
        type = getArguments().getInt("type", 0);
    }

    private void getData() {


        HttpMethods.getInstance().getLeaderWeiBaoTask(UserInfoUtil.getCurrentUserAccessToken(), type + 1, pageNo)
                .subscribe(new SampleRefreshObserver<List<Task>>(getContext(),refreshLayout) {
                    @Override
                    public void onNext(List<Task> tasks) {
                        super.onNext(tasks);
                        if (isRefresh) {
                            mTasks.clear();
                        }

                        if (tasks.size() > 0) {
                            mTasks.addAll(tasks);
                            pageNo++;
                        }

                        adapter.notifyDataSetChanged();
                        loadfinish = true; // 加载完成
                    }

                });

    }

    private void setAdapter() {
        // 设置refreshLayout的监听
        refreshLayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.BLUE,
                Color.GREEN);
        refreshLayout.setOnRefreshListener(this);

        mListView.setLayoutManager(new LinearLayoutManager(getContext()));
        mListView.addItemDecoration(new DividerItemDecoration(getContext(),
                DividerItemDecoration.VERTICAL_LIST, getResources()
                .getDrawable(R.drawable.drvice_10)));

        MultiItemTypeAdapter multiItemTypeAdapter = new MultiItemTypeAdapter(
                getContext(), mTasks);
        multiItemTypeAdapter.addItemViewDelegate(new WaitDelagate());
        multiItemTypeAdapter.addItemViewDelegate(new SignDelagate());
        multiItemTypeAdapter.addItemViewDelegate(new DetectDelagate());
        multiItemTypeAdapter.addItemViewDelegate(new FinishDelagate());

        adapter = new EmptyWrapper(multiItemTypeAdapter);

        View emptyView = inflater.inflate(R.layout.empty_view_text_and_image,
                container, false);
        ImageView ivEmptyTip = (ImageView) emptyView
                .findViewById(R.id.ivEmptyTip);
        TextView tvEmptyTip = (TextView) emptyView
                .findViewById(R.id.tvEmptyTip);
        ivEmptyTip.setImageResource(R.mipmap.tip_empty_huodong);
        tvEmptyTip.setText(R.string.NO_DATA);
        adapter.setEmptyView(emptyView);

        mListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
        mListView.addOnScrollListener(new OnRcvScrollListener() {
            @Override
            public void onBottom() {
                super.onBottom();
                if (loadfinish) {
                    Log.e("加载到底部 pageNo = ", pageNo + "");
                    loadMore();
                }

            }
        });
    }

    public class WaitDelagate implements ItemViewDelegate<Task> {

        @Override
        public int getItemViewLayoutId() {
            return R.layout.item_maintenance_mytask_wait;
        }

        @Override
        public boolean isForViewType(Task item, int position) {
            return item.getStatus() == 0;
        }

        @Override
        public void convert(ViewHolder holder, final Task task,
                            final int position) {
            holder.setText(R.id.tvCompany, task.getTask_name());
            holder.setText(R.id.tvDate, task.getTask_time());
            holder.setText(R.id.tvInfo, task.getParticipants());
            holder.setText(R.id.tvUsername, task.getTask_user_name());
            holder.setText(R.id.tvAssginTip, "派发对象：");
            holder.setText(R.id.tvAccept, "撤回任务");
            holder.setBackgroundRes(R.id.tvAccept,
                    R.drawable.round_task_state_red);
            holder.setOnClickListener(R.id.tvAccept, new OnClickListener() {

                @Override
                public void onClick(View v) {
                    deleteId = task.getId();
                    deletePosition = position;
                    mConfirmPopView.showPopWindow();
                }
            });
        }
    }

    public class SignDelagate implements ItemViewDelegate<Task> {

        @Override
        public int getItemViewLayoutId() {
            return R.layout.item_maintenance_mytask_sign;
        }

        @Override
        public boolean isForViewType(Task item, int position) {
            return item.getStatus() == 1;
        }

        @Override
        public void convert(ViewHolder holder, final Task task,
                            final int position) {
            holder.setText(R.id.tvCompany, task.getTask_name());
            holder.setText(R.id.tvDate, task.getTask_time());
            holder.setText(R.id.tvInfo, task.getParticipants());
            holder.setText(R.id.tvUsername, task.getTask_user_name());
            holder.setText(R.id.tvAssginTip, "派发对象：");
            holder.setVisible(R.id.tvSign, false);
        }
    }

    public class DetectDelagate implements ItemViewDelegate<Task> {

        @Override
        public int getItemViewLayoutId() {
            return R.layout.item_maintenance_mytask_detect;
        }

        @Override
        public boolean isForViewType(Task item, int position) {
            return item.getStatus() == 2;
        }

        @Override
        public void convert(final ViewHolder holder, final Task task,
                            final int position) {

            holder.setText(R.id.tvCompany, task.getTask_name());
            holder.setText(R.id.tvDate, task.getTask_time());
            holder.setText(R.id.tvUsername, task.getTask_user_name());
            holder.setText(R.id.tvAssginTip, "派发对象：");
            holder.setText(R.id.tvInfo, task.getParticipants());
            holder.setOnClickListener(R.id.tvWatchSignPic,
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            if (TextUtils.isEmpty(task.getSignImage())) {
                                ToastUtil.getInstances().showMsg("无法找到该图片~");
                                return;
                            }
                            final String[] urls = new String[1];
                            urls[0] = task.getSignImage();
                            Intent intent = new Intent(v.getContext(),
                                    ImagePagerActivity.class);
                            intent.putExtra(
                                    ImagePagerActivity.EXTRA_IMAGE_URLS, urls);
                            intent.putExtra(
                                    ImagePagerActivity.EXTRA_IMAGE_INDEX, 0);
                            v.getContext().startActivity(intent);
                        }
                    });
            holder.setOnClickListener(R.id.tvChooseMember,
                    new OnClickListener() {

                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(v.getContext(),
                                    JoinMemberReadActivity.class);
                            intent.putExtra("memberList",
                                    new Gson().toJson(task.getPartMembers()));
                            startActivity(intent);
                        }
                    });

            if (task.getItemStatus() != 2 && task.getPartMembers() != null
                    && task.getPartMembers().size() > 0) {
                task.setItemStatus(1);
            }

            switch (task.getItemStatus()) {
                case 1:
                    // 显示已参与的成员
                    holder.setVisible(R.id.tvJoinMember, true);
                    holder.setText(R.id.tvJoinMember, "开始检测");
                    holder.setVisible(R.id.rlDetect, false);
                    holder.setVisible(R.id.llMember, true);
                    holder.setVisible(R.id.tvJoinMember, false);
                    break;
                default:
                    holder.setVisible(R.id.tvJoinMember, true);
                    holder.setText(R.id.tvJoinMember, "选择参与成员");
                    holder.setVisible(R.id.rlDetect, false);
                    holder.setVisible(R.id.llMember, false);
                    holder.setVisible(R.id.tvJoinMember, false);
                    break;
            }

        }
    }

    public class FinishDelagate implements ItemViewDelegate<Task> {

        @Override
        public int getItemViewLayoutId() {
            return R.layout.item_maintenance_mytask_finish;
        }

        @Override
        public boolean isForViewType(Task item, int position) {
            return item.getStatus() == 3;
        }

        @Override
        public void convert(ViewHolder holder, final Task task, int position) {
            holder.setText(R.id.tvCompany, task.getTask_name());
            holder.setText(R.id.tvDate, task.getTask_time());
            holder.setText(R.id.tvUsername, task.getTask_user_name());
            holder.setText(R.id.tvAssginTip, "派发对象：");
            holder.setText(R.id.tvInfo, task.getParticipants());
            holder.setOnClickListener(R.id.tvDetail, new OnClickListener() {

                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(v.getContext(),
                            MaintenanceTaskDetailActivity.class);
                    intent.putExtra("id", task.getId());
                    startActivity(intent);
                }
            });
        }
    }

    /**
     * @author: HYM
     * @Title: doAllFinish
     * @Description: TODO(执行全部检测完成的动作) void
     * @date: 2017-9-11
     */
    void doAllFinish(String id, String remark, final int position,
                     final int func) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN,
                UserInfoUtil.getCurrentUserAccessToken());
        params.put("id", id);
        params.put("remark", remark);

        VolleyRequest.StringRequestPost(getContext(),
                WebApi.MAINTENANCE_ALL_DETECT_FINISH, "", params,
                new StringInterface(getContext()) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                EventBus.getDefault().post(
                                        new MaintenanceTaskListEvent(type,
                                                position, func));

                            } else if (status.equals("404")
                                    && info.contains("尚未登录")) {
                                ToastUtil.getInstances().showMsg(
                                        "尚未登录或该用户在其他地方登录，请重新登录！");
                                // 清除环信登录
                                UserHelp.getInstance().clearUser(
                                        AppBase.Context, true);
                                return;
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                        }
                    }

                    @Override
                    public void stringError(VolleyError error) {
                        ToastUtil.getInstances().showMsg(
                                R.string.err_http_response);
                    }
                });
    }

    void doDelete(String id, final int position) {
        Map<String, String> params = new HashMap<String, String>();
        params.put(AppConfig.ACCESS_TOKEN,
                UserInfoUtil.getCurrentUserAccessToken());
        params.put("id", id);
        dialog = DialogTool.showDialog(dialog, getContext());
        VolleyRequest.StringRequestPost(getContext(),
                WebApi.MAINTENANCE_LEADER_DELETE_NO_RECIVE_WBTASK, "", params,
                new StringInterface(getContext()) {

                    @Override
                    public void stringSuccess(String result) {
                        try {
                            JSONObject obj = new JSONObject(result);
                            String status = obj.getString("status");
                            String info = obj.getString("info");
                            if (status.equals("200")) {
                                ToastUtil.getInstances().showMsg(info);
                                mTasks.remove(position);
                                adapter.notifyDataSetChanged();
                            } else if (status.equals("404")
                                    && info.contains("尚未登录")) {
                                ToastUtil.getInstances().showMsg(
                                        "尚未登录或该用户在其他地方登录，请重新登录！");
                                // 清除环信登录
                                UserHelp.getInstance().clearUser(
                                        AppBase.Context, true);
                                return;
                            } else {
                                ToastUtil.getInstances().showMsg(info);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        } finally {
                            DialogTool.hideDialog(dialog);
                        }

                    }

                    @Override
                    public void stringError(VolleyError error) {
                        DialogTool.hideDialog(dialog);
                        ToastUtil.getInstances().showMsg(
                                R.string.err_http_response);
                    }
                });
    }

    @Override
    public void onRefresh() {
        // getData();
        isRefresh = true;
        pageNo = 1;
        mHandler.sendEmptyMessage(LOAD_DATA);
    }

    /**
     * 处理中心
     */
    Handler mHandler = new Handler() {
        public void dispatchMessage(android.os.Message msg) {
            switch (msg.what) {
                case LOAD_DATA:
                    if (loadfinish) {
                        loadfinish = false;
                        getData();
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    /**
     * 作者：hym 日期：2017-4-6 描述：加载更多数据
     */
    void loadMore() {
        isRefresh = false;
        mHandler.sendEmptyMessage(LOAD_DATA);
    }

    @Override
    public void OnDeleteListener() {
        doDelete(deleteId, deletePosition);
        mConfirmPopView.hidePopWindow();
    }

    @Override
    public void OnCancleListener() {
    }

    @Override
    public void OnShowListener() {

    }

    @Override
    public void OnHideListener() {
        deleteId = "";
        deletePosition = -1;
    }
}
